import React, {Component} from "react";
import {observer, inject} from "mobx-react";
import {findDOMNode} from "react-dom"
import {withRouter, Link} from "react-router-dom";
import {ListPage} from "weaver-mobile-page";
import {PullToRefresh, Icon, Grid, List, Modal, Tools, Toast} from "weaver-mobile";
import {ColorPercent} from "../../public/cptColorPercent/cptColorPercent"
import {gridData, instockDataTemplate, myAssetDataTemplate} from "./template";
import {_scanQRCode} from "../../util";
import * as API from "../../api/cptApi";

const getLabel = Tools.getLabel;


@inject("homeStore")
@withRouter
@observer
export default class Home extends Component {
    componentWillMount() {
        this.props.homeStore.init()
    }

    componentDidMount() {
        const {homeStore: {setVisualHeight}} = this.props;
        const tabBar = document.querySelector(".am-tab-bar-bar");
        const height = document.documentElement.clientHeight - findDOMNode(this.ptr).offsetTop - tabBar.clientHeight;
        setVisualHeight(height);
    }

    componentWillReceiveProps() {
        this.props.homeStore.init()
    }

    toAsset = (id) => {
        const {history} = this.props;
        history.push("/index/asset")
    };

    onGirdClink = (e) => {
        const {history} = this.props;
        if (e.link === "/operations/scan") {
            _scanQRCode((res) => {
                if (res) {
                    const params = {
                        scantype: "view",
                        mark: res
                    };
                    API.scanQRCodeCapital(params).then(res => {
                        if (res.flag) {
                            history.push("/assetInfo/infoCard/" + res.capitalid);
                        } else {
                            Toast.fail(res.msg, 2);
                        }
                    })
                }
            });
        } else {
            const right = window.cpt_page_right;
            const link = e.link.replace("/operations/", "");

            if (right[link] === true) {
                history.push(e.link)
            } else if (right["InStockCheck"] === true && e.link === "/acceptance/0") {
                history.push(e.link)
            } else {
                Toast.fail(right.msg, 2);
            }
        }
    };

    render() {
        const {homeStore} = this.props;
        const {visualHeight, dirDown, refreshing, sum, options} = homeStore;
        const {init} = homeStore;
        return (<div>
            <PullToRefresh
                damping={500}
                ref={el => this.ptr = el}
                style={{
                    height: visualHeight,
                    overflow: "scroll",
                    WebkitOverflowScrolling: "touch"
                }}
                direction={dirDown ? "down" : "up"}
                refreshing={refreshing}
                onRefresh={() => init()}
                distanceToRefresh={50}
            >
                <div style={{background: "#fff",minHeight:visualHeight}}>
                    <div style={{background: "#efeff5"}}>
                        <div className="h-list-box">
                            <div className="h-list-top-bar">
                                <div className='h-list-top-title'>{getLabel(389857, "当前资产情况")}</div>
                            </div>
                            <div className="h-info-content">
                                <div className="h-info-left">
                                    <div className="h-info-item">
                                        <div className="h-info-item-text">{getLabel(388246, "总数")}</div>
                                        <div className="h-info-item-num">
                                            <div className="h-info-sum">
                                                {sum}
                                                <Icon type='right' className='h-info-more'/>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div className="h-info-right">
                                    {options.map((item, index) => (
                                        <div key={index} className="h-info-item">
                                            <div className="h-info-item-text">{item.title}</div>
                                            <div className="h-info-item-num">
                                            <span style={{borderBottom: "2px solid" + item.colorBegin}}>
                                                {item.num}</span>
                                            </div>
                                        </div>
                                    ))}

                                </div>
                            </div>
                            <div className="h-color-percent-box">
                                <ColorPercent
                                    className='h-color-percent'
                                    options={options}
                                    borderRadiusNum={2}
                                    needStep={true}
                                    stepRange={{min: 2, max: 25}}
                                    onTouch={(a, b) => {
                                        // console.log(a, b)
                                    }}
                                />
                            </div>
                        </div>
                        <div className='h-list-box'>
                            <Grid data={gridData}
                                  itemStyle={{
                                      width: "25%",
                                      height: 90,
                                      borderRight: "1px solid #eee",
                                      borderBottom: "1px solid #eee"
                                  }}
                                  hasLine={false}
                                  isCarousel
                                  onClick={
                                      e1 => this.onGirdClink(e1)
                                  }
                            />
                        </div>
                        <ListContent/>
                    </div>

                </div>
            </PullToRefresh>
        </div>)
    }
}

@inject("homeStore")
@withRouter
@observer
class ListContent extends Component {
    toAssetDetail = (id) => {
        this.props.history.push("/assetInfo/infoCard/" + id)
    };
    toAcceptanceDetail = (id) => {
        if (window.cpt_page_right["InStockCheck"] === true) {
            this.props.history.push("/acceptanceDetail/" + id)
        } else {
            Toast.fail(window.cpt_page_right["msg"], 2)
        }
    };
    toAcceptance = () => {
        if (window.cpt_page_right["InStockCheck"] === true) {
            this.props.history.push("/acceptance/0")
        } else {
            Toast.fail(window.cpt_page_right["msg"], 2)
        }
    };

    render() {
        const {homeStore} = this.props;
        const {myAssetData, instockData, isright1, isright2} = homeStore;
        return (<div className='h-list-wrapper'>
            <div className="h-list-box">
                <div className="h-list-top-bar">
                    <div className='h-list-top-title'>{getLabel(389864, "待验收资产")}</div>
                    <div className='h-list-top-more' onClick={() => this.toAcceptance()}>
                        {getLabel(17499, "更多")}
                        <Icon type='right' size='md'/>
                    </div>
                </div>
                <div className="h-list-content">
                    {!isright1 || !instockData.data || instockData.data.length === 0 ?
                        <div className='h-list-none'>{getLabel(83553, "暂无数据")}</div> :
                        <List>
                            {this.instockRender()}
                        </List>
                    }
                </div>
            </div>
            <div className="h-list-box">
                <div className="h-list-top-bar">
                    <div className='h-list-top-title'>{getLabel(1209, "我的资产")}</div>
                    <Link to='/index/asset' className='h-list-top-more'>
                        {getLabel(17499, "更多")}
                        <Icon type='right' size='md'/>
                    </Link>
                </div>
                <div className="h-list-content">
                    {!isright2 || !myAssetData.data || myAssetData.data.length === 0 ?
                        <div className='h-list-none'>{getLabel(83553, "暂无数据")}</div> :
                        <List>
                            {this.myAssetRender()}
                        </List>
                    }
                </div>
            </div>
        </div>)
    }

    instockRender = () => {
        const {instockData, doInstockDelete} = this.props.homeStore;
        const fields = [];
        instockData.data.forEach((item, index) => {
            fields.push(<ListPage.Item
                key={index}
                data={item}
                template={instockDataTemplate}
                onClick={() => this.toAcceptanceDetail(item.tmpid)}
                withSwipeAction
                swipeActionProps={{
                    right: [
                        {
                            text: getLabel(15358, "作废"),
                            style: {backgroundColor: "#aaa", color: "white", padding: "0 5px"},
                            onPress: () => {
                                Modal.alert(getLabel(389858, "验收作废"), getLabel(389859, "确定作废该条目吗") + "?", [
                                    {
                                        text: getLabel(31129, "取消"), onPress: () => {
                                        }
                                    },
                                    {text: getLabel(826, "确定"), onPress: () => doInstockDelete(item.tmpid)}])
                            },
                        },

                    ]
                }}
            />);
        });
        return fields;
    };
    myAssetRender = () => {
        const {homeStore, history} = this.props;
        const {myAssetData} = homeStore;
        const {onBack, onRepair, onDelete} = homeStore;
        const fields = [];
        myAssetData.data.forEach((item, index) => {
            let right = [];
            if (JSON.parse(item["opt_back"])) {
                right.push({
                    text: getLabel(1384, "归还"),
                    style: {backgroundColor: "#2196f3", color: "white", padding: "0 5px"},
                    onPress: () => {
                        Modal.alert(getLabel(15305, "资产归还"), getLabel(389860, "需要归还该资产吗") + "?", [
                            {
                                text: getLabel(31129, "取消"), onPress: () => {
                                }
                            },
                            {text: getLabel(826, "确定"), onPress: () => onBack(item.id, "backMyCpt")}])
                    },
                })
            }
            if (JSON.parse(item["opt_mend"])) {
                right.push({
                    text: getLabel(83557, "送修"),
                    style: {backgroundColor: "#ef1322", color: "white", padding: "0 5px"},
                    onPress: () => {
                        Modal.alert(getLabel(22459, "资产送修"), getLabel(389862, "需要送修该资产吗") + "?", [
                            {
                                text: getLabel(31129, "取消"), onPress: () => {
                                }
                            },
                            {text: getLabel(826, "确定"), onPress: () => onRepair(history, item)}])
                    },
                })
            }
            if (JSON.parse(item["opt_delete"])) {
                right.push({
                    text: getLabel(91, "删除"),
                    style: {backgroundColor: "#aaa", color: "white", padding: "0 5px"},
                    onPress: () => {
                        Modal.alert(getLabel(389861, "资产删除"), getLabel(389863, "确定删除该资产吗") + "?", [
                            {
                                text: getLabel(31129, "取消"), onPress: () => {
                                }
                            },
                            {text: getLabel(826, "确定"), onPress: () => onDelete(item.id)}])
                    },
                })
            }
            fields.push(<ListPage.Item
                key={index}
                data={item}
                template={myAssetDataTemplate}
                onClick={() => this.toAssetDetail(item.id)}

                withSwipeAction={true}
                swipeActionProps={{
                    right: right
                }}
            />);
        });
        return fields;
    };

}
